package org.dawnmew.simplejar;

/**
 * Allows the creation of a single compressed JAR archive.
 *
 * @author dawnmew
 * @since 1.0
 *
 * Licensed under the MIT License.
 *
 * Copyright (c) 2012 dawnmew
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
import java.io.*;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;

public class JarBuilder
{

    private JarOutputStream jarFile = null;
    private boolean verboseMode = false;
    private static final int bufferSize = 32768;

    public JarBuilder(String filename)
    {
        try
        {
            jarFile = new JarOutputStream(new FileOutputStream(filename));
        } catch (Exception ex)
        {
            System.err.println("Couldn't open JarOutputStream: " + filename);
        }
    }

    public boolean isValid()
    {
        return jarFile != null;
    }

    public void setVerboseMode(boolean verboseMode)
    {
        this.verboseMode = verboseMode;
    }

    public void createFolder(String foldername)
    {
        if (!isValid())
        {
            return;
        }
        if (!foldername.endsWith("/"))
        {
            foldername += "/";
        }
        try
        {
            jarFile.putNextEntry(new ZipEntry(foldername));
            jarFile.closeEntry();
        } catch (IOException ex)
        {
            System.err.println("Couldn't create JarBuilder folder: " + foldername);
        }
    }

    public void addFileFromStream(byte[] input, String filename)
    {
        if (!isValid())
        {
            return;
        }
        if (verboseMode)
        {
            System.out.println("Compressing: " + filename);
        }
        try
        {
            jarFile.putNextEntry(new ZipEntry(filename));
            jarFile.write(input);
            jarFile.closeEntry();
        } catch (Exception ex)
        {
            System.err.println("Couldn't push file to jar: " + filename);
        }
    }

    public void addFileFromStream(Byte[] input, String filename)
    {
        byte[] arg = new byte[input.length];
        for (int i = 0; i < input.length; i++)
        {
            arg[i] = input[i].byteValue();
        }
        addFileFromStream(arg, filename);
    }

    public void addFileFromStream(InputStream inputStream, String filename)
    {
        ByteArrayOutputStream extensibleList = new ByteArrayOutputStream();
        try
        {
            int i;
            byte[] buffer = new byte[bufferSize];
            while ((i = inputStream.read(buffer)) > 0)
            {
                extensibleList.write(buffer,0,i);
            }
            addFileFromStream(extensibleList.toByteArray(), filename);
        } catch (IOException ex)
        {
            System.err.println("Couldn't push streamed file to jar: " + filename);
        }
    }

    public void addFileFromDisk(File fileHandler, String jarFilename)
    {
        try
        {
            if (fileHandler.isDirectory())
            {
                File[] listOfFiles = fileHandler.listFiles();
                if (!jarFilename.endsWith("/"))
                {
                    jarFilename += "/";
                }
                if (listOfFiles != null)
                {
                    for (int i = 0; i < listOfFiles.length; i++)
                    {
                        addFileFromDisk(listOfFiles[i], jarFilename + listOfFiles[i].getName());
                    }
                }
            } else
            {
                addFileFromStream(new FileInputStream(fileHandler), jarFilename);
            }
        } catch (FileNotFoundException ex)
        {
            System.err.println("Couldn't push disk file \"" + fileHandler.getName() + "\" to jar: " + jarFilename);
        }
    }

    public void addFileFromDisk(String diskFilename, String jarFilename)
    {
        try
        {
            addFileFromStream(new FileInputStream(diskFilename), jarFilename);
        } catch (FileNotFoundException ex)
        {
            System.err.println("Couldn't push disk file \"" + diskFilename + "\" to jar: " + jarFilename);
        }
    }

    public void addFolderFromDisk(String folderPath, String jarFolderName, boolean includeSubfolders)
    {
        if (!isValid())
        {
            return;
        }
        if (folderPath.endsWith("/"))
        {
            folderPath = folderPath.substring(0, folderPath.length() - 2);
        }
        File dir = new File(folderPath);
        if (!dir.isDirectory())
        {
            System.err.println("Couldn't open directory in JarBuilder because it's not a directory: " + folderPath);
            return;
        }

        if (jarFolderName == null)
        {
            jarFolderName = "";
        }

        if (!jarFolderName.isEmpty())
        {
            jarFolderName += "/";
        }

        if (verboseMode)
        {
            System.out.println("Compressing folder from disk: " + folderPath);
        }

        File[] listOfFiles = dir.listFiles();
        if (listOfFiles != null)
        {
            for (int i = 0; i < listOfFiles.length; i++)
            {
                if (listOfFiles[i].isFile() || includeSubfolders)
                {
                    addFileFromDisk(listOfFiles[i], jarFolderName + listOfFiles[i].getName());
                }
            }
        }

        if (verboseMode)
        {
            System.out.println("Folder compressed successfully!");
        }
    }

    public void close()
    {
        if (!isValid())
        {
            return;
        }
        try
        {
            jarFile.close();
        } catch (IOException ex)
        {
            System.err.println("Couldn't close JarBuilder instance.");
        }
        jarFile = null;
    }
}
